import { fetchList, refreshTable } from ".";
import { meassageMap } from "@userList/utils";
import { drawerLoading, drawerVisible, drawer_tablePage } from "./drawer";
import {
  drawerFormState,
  labelOptions,
  operateType,
  tmpLabelOptions,
  totalTagCount,
  set_formState,
  defaultDataSource,
  tableActiveKey,
} from "./store";
import { tableLoading } from "./table";
export const fetchLabelDataById = async ({
  formState,
  record,
  handleType,
  type,
}: any = {}) => {
  try {
    tableLoading.value = true;
    const res = await labelApi.queryDataById({
      infoId: record?.tag_id,
      type: type,
    });
    set_formState(handleType, formState, res.data);
    return res.data;
  } catch (error: any) {
    message.error(error.message);
  } finally {
    tableLoading.value = false;
  }
};

export const fetchLabelGDataById = async (params = {}) => {
  try {
    tableLoading.value = true;
    const res: any = await labelApi.queryDataByIdG(params);
    const {
      data: {
        attributes = {},
        userTag = [],
        userTagData = [],
        info = {},
        tagIds = [],
      },
    } = res;
    labelOptions.value = userTagData.map(
      ({ status, tag_id, tag_name }: any) => ({
        label: tag_name,
        value: tag_id,
        status: status,
      })
    );
    tmpLabelOptions.value = deepClone(labelOptions.value);
    if (operateType.value === "update") {
      drawerFormState.attr_id = +info.attr_id != 0 ? info.attr_id : undefined;
      drawerFormState.attr_name = info.attr_name;
      drawerFormState.remark = info.remark;
      drawerFormState.tagIds = tagIds;
      drawerFormState.type = info.type;
      defaultDataSource[2].value = userTag.map(
        ({ relate_time, status, tag_id, tag_name }: any) => ({
          relate_time,
          status,
          tag_id,
          tag_name,
        })
      );
      defaultDataSource[1].value = defaultDataSource[2].value.slice(
        (drawer_tablePage.current - 1) * drawer_tablePage.pageSize,
        drawer_tablePage.current * drawer_tablePage.pageSize
      );
      drawer_tablePage.total = attributes.total;
      totalTagCount.value = attributes.total;
    }
  } catch (error: any) {
    message.error(error.message);
  } finally {
    tableLoading.value = false;
  }
};

export const fetchDetail = async (params = {}) => {
  try {
    tableLoading.value = true;
    const res: any = await labelApi.selectDataByIdG(params);
    const {
      data: { detail = {}, attributes = {}, userTag = [] },
    } = res;
    drawerFormState.attr_id = +detail.attr_id != 0 ? detail.attr_id : undefined;
    drawerFormState.attr_name = detail.attr_name;
    drawerFormState.remark = detail.remark;
    drawerFormState.type = detail.type;

    defaultDataSource[2].value = userTag.map(
      ({ relate_time, status, tag_id, tag_name }: any) => ({
        relate_time,
        status,
        tag_id,
        tag_name,
      })
    );

    defaultDataSource[1].value = defaultDataSource[2].value.slice(
      (drawer_tablePage.current - 1) * drawer_tablePage.pageSize,
      drawer_tablePage.current * drawer_tablePage.pageSize
    );
    drawer_tablePage.total = attributes.total;
    totalTagCount.value = attributes.total;
  } catch (error: any) {
    message.error(error.message);
  } finally {
    tableLoading.value = false;
  }
};
const defineSubmitApiMap = (string, number, formState) => {
  const tableData = defaultDataSource[2];
  const basicForm = {
    type: formState.type,
  };
  const basicLabelForm = {
    tag_name: formState.tag_name,
    status: formState.status,
    explain: formState.explain,
  };
  const basicLableGroupForm = {
    attr_name: formState.attr_name,
    remark: formState.remark,
    tagIds: tableData.value.map(({ tag_id }: any) => tag_id),
  };
  const basicLabelAndLabelGroupForm = {
    attr_id: formState.attr_id,
  };
  const createLabel = () =>
    labelApi.create({
      ...basicForm,
      ...basicLabelForm,
      ...basicLabelAndLabelGroupForm,
    });
  const updateLabel = () =>
    labelApi.update({
      tag_id: formState.tag_id,
      ...basicForm,
      ...basicLabelForm,
      ...basicLabelAndLabelGroupForm,
    });
  const createLabelGroup = () =>
    labelApi.createG({
      ...basicForm,
      ...basicLableGroupForm,
    });
  const updateLabelGroup = () =>
    labelApi.updateG({
      ...basicForm,
      ...basicLableGroupForm,
      ...basicLabelAndLabelGroupForm,
    });
  const apiMap = new Map([
    [{ key: "add", state: 0 }, createLabel],
    [{ key: "update", state: 0 }, updateLabel],
    [{ key: "add", state: 1 }, createLabelGroup],
    [{ key: "update", state: 1 }, updateLabelGroup],
  ]);
  return apiMap;
};
const handleSubmitApiTask = async (string, number = 0, formState) => {
  try {
    const loading = drawerLoading;
    const visible = drawerVisible;
    let [, api]: any = [...defineSubmitApiMap(string, number, formState)].find(
      ([object]) => object.key == string && object.state == number
    );
    loading.value = true;
    const result: any = await api(formState);
    if (result.code != 200) return message.error(result.message);
    visible.value = false;
    const [, showMessage] = [...meassageMap(refreshTable, fetchList)].find(
      ([key]) => key.test(string)
    );
    showMessage();
  } catch (e: any) {
    message.error(e.message);
  } finally {
    drawerLoading.value = false;
  }
};
export const handleSubmit = () =>
  handleSubmitApiTask(operateType.value, tableActiveKey.value, drawerFormState);
